import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useModel } from 'umi';
import { CpasIcon, DevPopup } from "~/public/cpas-ui"
import { changeTitleTime, intl } from "@/utils";
import { confirm } from 'devextreme/ui/dialog';
import DataGrid, { AsyncRule, Column, CustomRule, Editing, Item, Paging, PatternRule, RequiredRule, Summary, Toolbar, TotalItem } from "devextreme-react/data-grid"
import { getAccountInfo, getDateAdd, getDateDelete, getDateList, getSubjectType } from "./service";
import notify from "devextreme/ui/notify";
import moment from 'moment';
import { Guid } from "guid-factory/lib/Guid";
// import { Lookup, SelectBox } from "devextreme-react";getDateUpdate,
import "./index.less"


export interface PropsDatas {
    width: string
    height: string
    button?: boolean,
    zcbfPartInfo?: any
}

const SetDataGrid = React.forwardRef((props: PropsDatas, ref) => {
    const { width, height, button, zcbfPartInfo } = props;

    const { initialState } = useModel('@@initialState');
    const { zcbfid, dbname, sjnd: zcbfSjnd } = initialState?.curPart as API.CurPart;

    const DataGridRef = useRef<any>();
    const ClickValue = useRef<any>();
    const ColumnIndex = useRef<any>();
    const DeleteRef = useRef<any>();
    const eventsSaveData = useRef<any>([]);
    const eventsNewRowKey = useRef<any>([]);
    const eventsNewPeriodData = useRef<any>([]);
    const periodValue = useRef<any>([]);

    const [perioddata, setPerioddata] = useState<any>([]);
    const [InfoDatas, setInfoData] = useState<any>([]);
    const newDataValue = useRef<any>({});
    const isDelAndAddTop = useRef<boolean>(true);
    // const [NewDatas, setNewData] = useState<any>({});
    // const [PreviousValue, setPreviousValue] = useState<string>('');
    // const [ByMonthData, setByMonthData] = useState<string>('');
    const [editstate, setEditstate] = useState<boolean>(true);

    function compare(property: any) {
        return property.sort((a: { sjnd: { match: (arg0: RegExp) => string; }; }, b: { sjnd: { match: (arg0: RegExp) => string; }; }) => {
            const year_a = parseInt(a.sjnd.match(/^\d+/));
            const year_b = parseInt(b.sjnd.match(/^\d+/));
            return year_a - year_b;
        });
    }

    const getAccountInfos = async () => {
        if (dbname) {
            const InfoData = await getAccountInfo({ dbname });
            setInfoData(InfoData);
        }
    }
    // 处理日期
    function convertDate(dateString: any) {
        const dateObj = new Date(dateString);
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 获取 期间列表
    // perioddata
    const getListData = async () => {
        const res = await getDateList({ zcbfid });
        res.forEach((item: any) => {
            item.ADateS = convertDate(item.ADateS);
            item.ADateE = convertDate(item.ADateE)
        });
        const resdata = compare(res);
        setPerioddata(resdata);
    }
    const justIsDelAndAdd = (bolData: boolean) => {
        isDelAndAddTop.current = bolData;
    }
    // 自定义方法
    useImperativeHandle(ref, () => ({
        restYearTable: () => {
            ClickValue.current = {};
            getListData();
            DataGridRef.current?.instance.refresh();
            getAccountInfos();
            setEditstate(true);
            justIsDelAndAdd(true);
        },
        saveEditData: () => {
            DataGridRef.current.instance.saveEditData();
        },
        initData: () => { return perioddata },

        getData: () => {
            return eventsSaveData.current;
        },

        getPeriodData: () => {

            // console.log(eventsSaveData.current, 'eventsSaveData.current-----');
            // console.log(eventsNewPeriodData.current, 'eventsNewPeriodData.current-----');

            const resFind = eventsNewPeriodData.current.filter((data: any) => {
                return eventsSaveData.current.some((r: any) => data.data_id.toString().includes(r.Data_ID));
            });

            // const uniqueArray = Array.from(resFind.reduce((map: { set: (arg0: any, arg1: any) => void; }, obj: { data_id: any; }) => {
            //     map.set(obj.data_id, obj);
            //     return map;
            // }, new Map()).values());
            const uniqueArray = Array.from(resFind.reduce((map: { set: (arg0: any, arg1: any) => void; }, obj: { data_id: { toString: () => any; }; }) => {
                const key = typeof obj.data_id === "string" ? obj.data_id : obj.data_id.toString();
                map.set(key, obj);
                return map;
            }, new Map()).values());

            if (uniqueArray.length <= 0) {
                const Newperioddata = perioddata.filter((item: any) => item.ByMonth === null)
                const newArray = Newperioddata.map((obj: { ADateE: string; Data_ID: string; sjnd: string; }) => {
                    const byMonth = obj.ADateE.substr(0, 4) + obj.ADateE.substr(5, 2);
                    const dataId = parseInt(obj.Data_ID);
                    return {
                        ByMonth: byMonth,
                        data_id: dataId,
                        datname: "期间设置时创建",
                        id: zcbfid,
                        nd: parseInt(obj.sjnd)
                    };
                });
                console.log(newArray, 'newArray------------');
                return newArray;
            } else {
                console.log(uniqueArray, 'uniqueArray---');
                return uniqueArray;
            }
        },

        restYearAllData: () => {
            ColumnIndex.current = null;
            ClickValue.current = {};
            eventsSaveData.current = [];
            eventsNewRowKey.current = [];
            eventsNewPeriodData.current = [];
            setPerioddata([]);
            DataGridRef.current?.instance.deselectAll();
        },

        checkContinuous: () => {
            return checkContinuousYear(perioddata);
        },

        checkDuplicate: () => {
            return checkDuplicateYear(perioddata)
        }
    }));

    // 判断 年度是否连续
    function checkContinuousYear(dataArray: any) {
        // 先按照时间顺序对对象数组进行排序
        dataArray.sort((a: { ADateS: number; }, b: { ADateS: number; }) => a.ADateS - b.ADateS);

        // 遍历数组，检查每个相邻对象的时间跨度是否为一年且连续
        for (let i = 0; i < dataArray.length - 1; i++) {
            const currDateEnd = new Date(dataArray[i].ADateE);
            const nextDateStart = new Date(dataArray[i + 1].ADateS);

            // 如果相邻对象的年份不连续，直接返回false
            if (currDateEnd.getFullYear() !== nextDateStart.getFullYear() - 1) {
                return false;
            }

            // 如果相邻对象的年份连续，但月份或日期的差距不为一年，也返回false
            if (
                currDateEnd.getMonth() !== 11
                || currDateEnd.getDate() !== 31
                || nextDateStart.getMonth() !== 0
                || nextDateStart.getDate() !== 1
            ) {
                return false;
            }
        }

        // 如果数组中所有对象的年月日都连续，则返回true
        return true;
    }

    //   判断 年度是否重复
    function checkDuplicateYear(arr: any) {
        // Step 1: 检查ID是否重复
        const years = arr.map((item: any) => parseInt(item.sjnd.match(/^\d+/)));
        for (let i = 0; i < years.length; i++) {
            for (let j = i + 1; j < arr.length; j++) {
                if (parseInt(arr[i].sjnd.match(/^\d+/)) === parseInt(arr[j].sjnd.match(/^\d+/))) {
                    return true;
                }
            }
        }

        // Step 2: 如果都没有重复，返回false
        return false;
    }



    // const contentReady = () => {
    //     console.log(editstate, 'editstate----');
    //     if (perioddata?.length) {
    //         if (editstate) {
    // const idnex = DataGridRef.current?.instance.getVisibleRows();
    // // console.log(NewDatas,'NewDatas----');
    // const tempData = idnex.filter((item: any) => {
    //     if (item.data.id === ClickValue.current.id) {
    //         return item
    //     }
    // });
    //             console.log(tempData, 'addRowYearaaa----------');
    //             if (tempData?.length) {
    //                 DataGridRef.current?.instance.deselectRows(ClickValue.current.id);
    //                 if (button) DataGridRef.current?.instance.selectRowsByIndexes(tempData[0].rowIndex);
    //             } else {
    //                 if (button) DataGridRef.current?.instance.selectRowsByIndexes(0);
    //             }
    //         } else {
    //             if (button) DataGridRef.current?.instance.selectRowsByIndexes(0);
    //         }
    //     } else {
    //         DataGridRef.current?.instance.deselectAll();
    //         ClickValue.current = {};
    //     }
    // }


    const deleteData = async (selectdata: any) => {
        DeleteRef.current.show({
            title: "提示",
            okCallback: async () => {
                if (perioddata.length === 1) {
                    notify("至少保留一个期间", 'error', 2000)
                } else {
                    console.log(selectdata, 'selectdata----');
                    if (selectdata) {
                        periodValue.current = selectdata.Data_ID;
                        const newData: any = { ...selectdata, rowState: 'delete' };
                        delete newData.where;
                        eventsSaveData.current.push(newData);
                        setPerioddata((item: any) => {
                            const newItemData: any[] = [...item];
                            const resFind = newItemData.filter((data: any) => data.id !== selectdata.id);
                            return compare(resFind);
                        });
                        const filteredArray = eventsNewPeriodData.current.filter((item: any) => item.data_id.toString() !== selectdata.Data_ID);
                        eventsNewPeriodData.current = filteredArray;
                        justIsDelAndAdd(true)
                        ClickValue.current = {};
                    }
                }
            }
        })
    };

    const changeYear = () => {
        const curYear = moment().format("YYYY");
        console.log(zcbfPartInfo, '@@@');
        let tempND: string;
        let newData: any = { id: Guid.newGuid(), rowState: 'insert' }
        let tempMooth: string;
        /*
        
        这一段注释掉，因为一定会有一个本年年度的数据
        // if (perioddata.length === 0 && zcbfPartInfo.aDateS && zcbfPartInfo.aDateE) {
        //     const yearSjnd = changeTitleTime(zcbfPartInfo.aDateS, zcbfPartInfo.aDateE);
        //     tempND = `${moment(zcbfPartInfo.aDateS).year()}`;
        //     const moothEND = moment(zcbfPartInfo.aDateE).month() + 1;
        //     tempMooth = moothEND > 9 ? `${moothEND}` : `0${moothEND}`;
        //     newData = {
        //         ...newData,
        //         Data_ID: `${tempND}`, sjnd: `${yearSjnd.titleTimeB}`,
        //         ADateS: zcbfPartInfo.aDateS, ADateE: zcbfPartInfo.aDateE, ByMonth: `${tempND}${tempMooth}`,
        //     };
        // } else {
        // }
 */
        if (ClickValue.current?.sjnd) {
            const yearMatch = ClickValue.current?.sjnd?.match(/\d{4}/);
            tempND = yearMatch ? `${yearMatch[0] * 1 - 1}` : curYear;
        } else {
            tempND = zcbfSjnd;
        }
        let arrYaerMooth = InfoDatas.filter((item: any) => item.Data_ID === tempND);
        if (arrYaerMooth?.length > 0 && arrYaerMooth[0]?.byMonth) {
            tempMooth = `${arrYaerMooth[0]?.byMonth}`?.slice(4) ?? '12';
        } else {
            tempMooth = '12';
        }
        newData = {
            ...newData,
            Data_ID: `${tempND}`, sjnd: `${tempND}年度`,
            ADateS: `${tempND}-01-01`, ADateE: `${tempND}-12-31`,
            ByMonth: `${tempND}${tempMooth}`,
        };

        const state = InfoDatas.some((item: any) => item.Data_ID === tempND);
        if (!state) {
            const newPeriodData = {
                id: zcbfid, nd: tempND, data_id: tempND, datname: "期间设置时创建", ByMonth: `${tempND}${tempMooth}`
            }
            eventsNewPeriodData.current.push(newPeriodData);
        };
        return newData;
    }


    const addRowYear = () => {
        setEditstate(true);
        justIsDelAndAdd(false);
        const newData = changeYear();
        // debugger;
        eventsNewRowKey.current.push(newData.id);
        eventsSaveData.current.push(newData);
        setPerioddata((item: any) => {
            const newItemData = [...item];
            newItemData.push(newData);
            return compare(newItemData);
        });
        ClickValue.current = newData;
    };

    // 右击 的显示操作
    // const dataMenuItems = (e: any) => {
    //     if (button) {
    //         // 数据上的菜单
    //         if (e.target == 'content' && e.row?.rowType == 'data') {
    //             e.items = [
    //                 {
    //                     icon: 'add',
    //                     text: intl('audit.paper.add', '添加'),
    //                     onItemClick: ((v: any) => {
    //                         console.log(e, v, '@@@');
    //                         // DataGridRef.current?.instance.selectRows(e.rowIndex, true);
    //                         ClickValue.current = e.row.data;
    //                         ColumnIndex.current = e.columnIndex;
    //                         addRowYear();
    //                     }),
    //                 },
    //                 {
    //                     icon: 'trash',
    //                     text: intl('audit.paper.del', '删除'),
    //                     onItemClick: (async () => {
    //                         deleteData(e.row.data);
    //                     })
    //                 },
    //             ]
    //         }
    //     }
    // };

    // 保存
    const PeriodSetting = (yearNDID: any) => {
        const state = InfoDatas.some((item: any) => item.Data_ID === yearNDID.toString());
        if (!state) {
            const newPeriodData = {
                id: zcbfid, nd: yearNDID, data_id: yearNDID, datname: "期间设置时创建", ByMonth: `${yearNDID}12`
            }
            eventsNewPeriodData.current.push(newPeriodData);
        }
    }

    function isWholeYear(yearString: string) {
        // 使用正则表达式匹配年份部分
        const yearRegex = /^\d{4}年/;
        const matchedYear = yearString.match(yearRegex);

        // 如果能成功匹配到四位数字作为年份，并且后面的部分是"1-12月"
        if (matchedYear && yearString.endsWith("1-12月")) {
            return true;
        }

        return false;
    }



    const changeDateFun = (data: any) => {
        const ByMonth = data.ByMonth?.toString().substr(data.ByMonth.toString().length - 2);
        console.log(ByMonth, 'ByMonth----');
        const getYearMonthData = (date: string) => {
            const year = moment(date).year();
            const month = moment(date).month() + 1;
            const formattedDate = moment(date).format('YYYY-MM-DD');
            return { year, month, formattedDate };
        };
        let yearNDID = '';
        let yearND = '';
        let moothSND = '';
        let moothEND = '';
        let moothSDataND = '';
        let moothEDataND = '';
        if (data.ADateE && data.ADateS) {
            const startData = getYearMonthData(data.ADateS);
            const endData = getYearMonthData(data.ADateE);

            if (newDataValue.current.ADateS) {
                if (startData.year !== endData.year) {
                    yearNDID = `${startData.year}`;
                    yearND = `${startData.year}年`;
                    moothSND = `${startData.month}`;
                    moothSDataND = startData.formattedDate;
                    moothEND = `-12月`;
                    moothEDataND = `${startData.year}-12-31`;
                } else {
                    yearNDID = `${startData.year}`;
                    yearND = `${startData.year}年`;
                    moothSND = `${startData.month}`;
                    moothSDataND = startData.formattedDate;
                    if (new Date(data.ADateE) < new Date(data.ADateS)) {
                        moothEND = `-12月`;
                        moothEDataND = `${startData.year}-12-31`;
                    } else {
                        moothEND = `-${endData.month}月`;
                        moothEDataND = endData.formattedDate;
                    }
                }
            } else {
                if (startData.year !== endData.year) {
                    yearNDID = `${endData.year}`;
                    yearND = `${endData.year}年`;
                    moothEND = `-${endData.month}月`;
                    moothEDataND = endData.formattedDate;
                    moothSND = `1`;
                    moothSDataND = `${endData.year}-01-01`;
                } else {
                    yearNDID = `${endData.year}`;
                    yearND = `${endData.year}年`;
                    moothEND = `-${endData.month}月`;
                    moothEDataND = endData.formattedDate;

                    if (new Date(data.ADateE) < new Date(data.ADateS)) {
                        moothSND = `1`;
                        moothSDataND = `${endData.year}-01-01`;
                    } else {
                        moothSND = `${startData.month}`;
                        moothSDataND = startData.formattedDate;
                    }
                }
            }
        } else {
            if (newDataValue.current.ADateS) {
                const startData = getYearMonthData(data.ADateS);
                yearNDID = `${startData.year}`;
                yearND = `${startData.year}年`;
                moothSND = `${startData.month}`;
                moothSDataND = startData.formattedDate;
                moothEND = `-12月`;
                moothEDataND = `${yearNDID}-12-31`;
            } else {
                const endData = getYearMonthData(data.ADateE);
                yearNDID = `${endData.year}`;
                yearND = `${endData.year}年`;
                moothSND = `1`;
                moothSDataND = `${yearNDID}-01-01`;
                moothEND = `-${endData.month}月`;
                moothEDataND = endData.formattedDate;
            }
        }

        return { yearND, yearNDID, moothSND, moothEND, moothSDataND, moothEDataND, ByMonth };
    };


    const rowStateChange = (rowData: any) => {
        const { data, key, type } = rowData;
        const { yearND, yearNDID, moothSND, moothEND, moothSDataND, moothEDataND, ByMonth } = changeDateFun(data);
        let newData: any;
        const newKey = eventsNewRowKey.current.find((item: any) => item === data.id);
        // debugger;
        if (newKey) {
            const inputString = `${yearND}${moothSND}${moothEND}`;
            const isYear = isWholeYear(inputString);
            newData = {
                Data_ID: yearNDID, id: key, sjnd: isYear ? `${yearND}${'度'}` : `${yearND}${moothSND}${moothEND}`,
                ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: 'insert'
            };
        } else {
            const inputString = `${yearND}${moothSND}${moothEND}`;
            const isYear = isWholeYear(inputString);
            newData = {
                Data_ID: yearNDID, id: key, sjnd: isYear ? `${yearND}${'度'}` : `${yearND}${moothSND}${moothEND}`,
                ADateS: moothSDataND, ADateE: moothEDataND, ByMonth: data.ByMonth ? `${yearNDID}${ByMonth}` : `${yearNDID}12`, rowState: type
            }
            if (newData.rowState === 'update') {
                newData = { ...newData, where: { guid: key } };
            }
            if (newData.rowState === 'delete') {
                delete newData.where;
            }
            if (newData.rowState === 'insert') {
                eventsNewRowKey.current.push(key);
            }
        }
        PeriodSetting(yearNDID);
        if (newData.rowState !== 'delete') {
            setPerioddata((item: any) => {
                let newItemData = [...item];
                const resFind = newItemData.find((data: any) => data.id && data.id === key);
                if (resFind) {
                    newItemData = newItemData.map((item: { id: string; }) => {
                        if (item.id === key) {
                            return newData;
                        }
                        return item;
                    });
                } else {
                    newItemData.push(newData);
                }
                return compare(newItemData);
            });
        }
        return newData;
    }

    const SavedData = (e: any) => {
        if (e.changes.length) {
            console.log(e, '@@@');
            if (!newDataValue.current) return;
            const { key } = e.changes[0];
            const newData = rowStateChange(e.changes[0]);
            const resFind = eventsSaveData.current.find((item: any) => item.id && item.id === key);
            if (resFind) {
                // console.log(resFind.ADateE, 'resFind----');
                // 修改更改的值
                eventsSaveData.current = eventsSaveData.current.map((item: { id: string; }) => {
                    if (item.id === key) {
                        return newData;
                    }
                    return item;
                });
            } else {
                eventsSaveData.current.push(newData);
            }
            ClickValue.current = newData;
            console.log(newData, '@@@ SavedData');

        }
    }

    // 对应账套 现不做编辑 后期看变化
    // const onValueChanged = async (cell: any, e: any) => {
    //     cell.setValue(e.value.Data_ID);
    //     setPreviousValue(e.value.Data_ID);
    //     // const type = await getSubjectType({
    //     //     dbname,
    //     //     Data_ID: e.value.Data_ID
    //     // });
    //     // setByMonthData(type[0].name)
    //     // console.log(type, 'r-------');
    //     // setPerioddata(r);
    // }
    // const statusEditorRender = (cell: any) => {
    //     return <SelectBox
    //         dataSource={InfoDatas}
    //         defaultValue={cell.value}
    //         {...cell.column.lookup}
    //         displayExpr="Data_ID"
    //         onValueChanged={(e) => onValueChanged(cell, e)}
    //     />;
    // }



    // const maxDate = new Date(`${zcbfSjnd * 1 - 1}-12-31`);
    const maxDateSjnd = new Date(`${zcbfSjnd}-12-31`);
    const maxDateSjndQc = new Date(`${zcbfSjnd}-1-1`);
    const validateDate = (params: any) => {
        if (params.data.Data_ID === zcbfSjnd) {
            return new Promise((resolve) => {
                const inputValue = new Date(params.value);
                if (inputValue > maxDateSjnd || inputValue < maxDateSjndQc) {
                    resolve({
                        isValid: false,
                        message: `所选日期必须在 ${zcbfSjnd}年期间`,
                    });
                } else {
                    resolve({
                        isValid: true,
                    });
                }
            });
        }
        return new Promise((resolve) => {
            const inputValue = new Date(params.value);
            if (inputValue > maxDateSjnd) {
                resolve({
                    isValid: false,
                    message: `所选日期必须小于 ${zcbfSjnd}-12-31`,
                });
            } else {
                resolve({
                    isValid: true,
                });
            }
        });
    };


    const contentReady = async () => {
        if (perioddata?.length) {
            if (button) {
                const idnex = await DataGridRef.current?.instance.getVisibleRows();
                if (!ClickValue.current?.id) {
                    DataGridRef.current?.instance.selectRowsByIndexes(0);
                    ClickValue.current = idnex[0]?.data ?? {};
                } else {
                    const tempData = idnex.filter((item: any) => {
                        if (item?.data?.id === ClickValue.current?.id) {
                            return item;
                        }
                    });
                    if (tempData.length) {
                        ClickValue.current = tempData[0]?.data;
                        DataGridRef.current?.instance.selectRowsByIndexes(tempData[0]?.rowIndex);
                    } else {
                        if (isDelAndAddTop.current) {
                            ClickValue.current = idnex[0]?.data;
                            DataGridRef.current?.instance.selectRowsByIndexes(idnex[0]?.rowIndex);
                        } else {
                            if (ClickValue.current.id === idnex[0]?.data.id) {
                                ClickValue.current = idnex[0]?.data;
                                DataGridRef.current?.instance.selectRowsByIndexes(idnex[0]?.rowIndex);
                            }
                        }

                    }

                }
            }

        } else {
            DataGridRef.current?.instance.deselectAll();
            ClickValue.current = {};
        }
    }

    return (
        <div style={{ width: "100%", height: "100%", display: 'flex', flexDirection: 'column' }}>
            {useMemo(() => {
                const lastElement = perioddata[perioddata.length - 1];
                return <DataGrid
                    width={width}
                    height={button ? '79%' : "100%"}
                    className='HomeGrid'
                    keyExpr="id"
                    dataSource={perioddata}
                    allowColumnReordering={true}
                    allowColumnResizing={true}
                    allowHeaderFiltering={false}
                    showBorders={true}
                    showRowLines={true}
                    ref={DataGridRef}
                    onSaved={SavedData}
                    onContentReady={contentReady}
                    onRowUpdating={(e: any) => {
                        newDataValue.current = e.newData;
                    }}
                    onCellClick={(v) => {
                        if (v.rowType === "header") return;
                        setEditstate(false);
                        if (v.rowIndex !== -1 && button) {
                            // && v.column?.caption !== "操作"
                            console.log(v.columnIndex, v.data, v, 'v.rowIndex---');
                            DataGridRef.current?.instance.selectRowsByIndexes(v.rowIndex);
                            ClickValue.current = v.data;
                            ColumnIndex.current = v.columnIndex;
                        }
                    }}
                    selection={{ mode: 'single' }}
                    columnResizingMode="widget"
                    columnMinWidth={70}
                    editing={{
                        // mode: 'batch',
                        mode: 'cell',
                        allowUpdating: button,
                        allowAdding: button,
                        startEditAction: 'click',
                        allowDeleting: false
                    }}
                >
                    <Paging enabled={false} />
                    <Toolbar>
                        <Item
                            location='before'
                            render={() => {
                                return <span style={{ fontWeight: "600", fontSize: "14px" }}>期间设置</span>
                            }}
                        />
                    </Toolbar>
                    <Column
                        caption={'期间'}
                        dataField="sjnd"
                        alignment='center'
                        allowEditing={false}
                        allowResizing={true}
                        width={110}
                    />
                    <Column
                        caption={'期初'}
                        dataField="ADateS"
                        alignment='center'
                        dataType="date"
                        allowResizing={true}
                    >
                        <AsyncRule
                            validationCallback={validateDate}
                        />
                    </Column>
                    <Column
                        caption={'期末'}
                        dataField="ADateE"
                        alignment='center'
                        dataType="date"
                        allowResizing={true}
                    >
                        <AsyncRule
                            validationCallback={validateDate}
                        />
                    </Column>
                    <Column
                        caption={'对应账套'}
                        dataField="Data_ID"
                        alignment='center'
                        dataType="Data_ID"
                        allowEditing={false}
                        allowResizing={true}
                    // 目前 不让设置
                    // editCellRender={statusEditorRender}
                    />
                    <Column
                        caption={'账套期间'}
                        dataField="ByMonth"
                        alignment='center'
                        allowEditing={false}
                        allowResizing={true}
                    />
                    <Column
                        caption={'操作'}
                        alignment='center'
                        visible={button}
                        fixed={true}
                        fixedPosition='right'
                        width={40}
                        cellRender={(cell: any) => {
                            // console.log(cell, '@@@');
                            if (cell?.data?.id !== lastElement?.id) {
                                return <CpasIcon type="icon-delete" onClick={() => {
                                    deleteData(cell.data);
                                }} />
                            }
                            return <></>
                        }}
                    />
                </DataGrid >
            }, [perioddata, InfoDatas, editstate])}
            {
                button ?
                    <div className="Text_Style" onClick={() => { addRowYear(); }} >
                        <span><CpasIcon type="icon-add-circle1" /> 新建</span>
                    </div>
                    : ''
            }
            <DevPopup.Default ref={DeleteRef} width={80} height={200}  >
                {() => {
                    return <span>是否要删除此记录？</span>
                }}
            </DevPopup.Default>
        </div>
    )
})
export default React.memo(SetDataGrid);
